package com.bytecollege.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytecollege.model.*;
import com.bytecollege.service.Impl.*;
import com.bytecollege.util.FileUploadUtil;
import com.bytecollege.vo.AremarkVo;
import com.bytecollege.vo.ArticleDetailVo;
import com.bytecollege.vo.ArticleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 讨论区模块
 */
@Controller
@RequestMapping("/article")
class ArticleController {
    @Autowired
    private ArticleServiceImpl articleService;
    @Autowired
    private AtypeServiceImpl atypeService;
    @Autowired
    private AremarkServiceImpl aremarkService;
    @Autowired
    private ArticleCollectServiceImpl articleCollectService;
    @Autowired
    private FootmarkServiceImpl footmarkService;


    /**
     * 获取讨论区文章数据，初始化后跳转到视图层
     * @param pageIndex
     * @param typeId
     * @param model
     * @return
     */
    @GetMapping("/forum")
    public String getAllArticle(
            @RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "typeId", defaultValue = "-1") String typeId,
            Model model){
        List<Atype> atypeList = atypeService.getAllAtype();
        model.addAttribute("atypeList",atypeList);
        Integer pageSize=10;
        if (pageIndex<=1){
            pageIndex = 1;
        }
        Page<ArticleVo> articleVoPage = new Page(pageIndex,pageSize);
        //是否根据typeId查询
        boolean isType = true;
        //-1不根据typeId查询
        if (typeId.equals("-1")) {
            isType = false;
        }
        IPage<ArticleVo> articleVoIPage = articleService.getAllArticle(articleVoPage,isType,typeId);
        List<ArticleVo> articleList = articleVoIPage.getRecords();
        List<ArticleVo> hotArticleList = articleService.getHotArticle();
        List<ArticleVo> readArticleList = articleService.getReadArticle();
        model.addAttribute("articleList",articleList);
        model.addAttribute("pageIndex",pageIndex);
        model.addAttribute("hotArticleList",hotArticleList);
        model.addAttribute("readArticleList",readArticleList);
        model.addAttribute("page",articleVoIPage);
        model.addAttribute("typeId",typeId);
        return "forum";
    }


    /**
     * 跳转到文章发表页面，完成初始化
     * @param message
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/publish" )
    public String publish(@RequestParam(value = "message", required = false) String message,Model model,HttpSession session){
        User user = (User)session.getAttribute("data");
        if (user == null){
            return "redirect:/user/tologin";
        }
        List<Atype> atypeList = atypeService.getAllAtype();
        model.addAttribute("message",message);
        model.addAttribute("atypeList",atypeList);
        return "publish";
    }

    /**
     * 发表文章
     * @param articleDetailVo
     * @return
     */
    @PostMapping("/addArticle")
    public String addArticle(ArticleDetailVo articleDetailVo, RedirectAttributes redirectAttributes,HttpSession session){
        User user = (User)session.getAttribute("data");
        if (user == null){
            return "redirect:/user/tologin";
        }
        if (articleDetailVo.getArticleTitle().equals("") || articleDetailVo.getArticleContent().equals("")){
            redirectAttributes.addAttribute("message","IsNull");
            return "redirect:publish";
        }
        Article article = Article.builder()
                .userId(user.getUserId())
                .articleTitle(articleDetailVo.getArticleTitle())
                .atypeId(articleDetailVo.getAtypeId())
                .articleContent(articleDetailVo.getArticleContent())
                .articleTime(new Date())
                .articleClicks(0)
                .articleState(0)
                .build();
        if (articleService.addArticle(article)>0){
            redirectAttributes.addAttribute("message","Success");
        }else{
            redirectAttributes.addAttribute("message","Failed");
        }
        return "redirect:publish";
    }

    /**
     * 通过文章编号删除文章
     */
    @GetMapping("delArticle")
    public String delArticle(@RequestParam(value = "articleId") Integer articleId, Model model,HttpSession session){
        //获取当前登录用户的信息
        User user = (User)session.getAttribute("data");
        if (user == null){
            return "redirect:/user/tologin";
        }
        if(articleService.delArticle(articleId)>0){
            model.addAttribute("msg","删除文章成功！");

        }else{
            model.addAttribute("msg","删除文章失败！");
        }
        return "redirect:publish";
    }

    /**
     * 通过文章编号查找一条文章，完成更新回显
     */
    @GetMapping("getArticleById")
    public String getArticleById(@RequestParam(value = "articleId") Integer articleId,@RequestParam(value = "message", required = false) String message,Model model,HttpSession session){
        //获取当前登录用户的信息
        User user = (User)session.getAttribute("data");
        if (user == null){
            return "redirect:/user/tologin";
        }
        List<Atype> atypeList = atypeService.getAllAtype();
        model.addAttribute("message",message);
        model.addAttribute("atypeList",atypeList);
        ArticleDetailVo article = articleService.getArticleById(articleId);
        model.addAttribute("article",article);
        return "updateArticle";
    }

    /**
     * 用户更新文章
     * @param article
     * @return
     */
    @PostMapping("modArticle")
    public String modArticle(Article article, RedirectAttributes redirectAttributes,HttpSession session){
        //获取当前登录用户的信息
        User user = (User)session.getAttribute("data");
        if (user == null){
            return "redirect:/user/tologin";
        }
        if (article.getArticleTitle().equals("") || article.getArticleContent().equals("")){
            redirectAttributes.addAttribute("message","IsNull");
            return "redirect:getArticleById?articleId="+article.getArticleId();
        }
        Article article1 = Article.builder()
                .articleId(article.getArticleId())
                .userId(user.getUserId())
                .articleTitle(article.getArticleTitle())
                .atypeId(article.getAtypeId())
                .articleContent(article.getArticleContent())
                .articleTime(new Date())
                .articleClicks(article.getArticleClicks())
                .articleState(1)
                .build();
        if (articleService.modArticle(article1)>0){
            redirectAttributes.addAttribute("message","Success");
        }else{
            redirectAttributes.addAttribute("message","Failed");
        }
        return "redirect:getArticleById?articleId="+article.getArticleId();
    }

    /**
     * 文章详情页内容查询
     * @param articleId
     * @param model
     * @return
     */
    @GetMapping("getArticleDetailById")
    public String getArticleDetailById(@RequestParam(value = "articleId") Integer articleId,@RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex,@RequestParam(value = "message", required = false) String message,Model model,HttpSession session){
        ArticleDetailVo article = articleService.getArticleById(articleId);
        //文章收藏量
        Integer collectNum = articleCollectService.getCollectNumByArticleId(articleId);
        Integer pageSize=5;
        if (pageIndex<=1){
            pageIndex = 1;
        }
        Page<AremarkVo> aremarkVoPage = new Page(pageIndex,pageSize);
        IPage<AremarkVo> aremarkVoIPage = aremarkService.getAremarkByArticleId(aremarkVoPage,articleId);
        List<AremarkVo> aremarkList = aremarkVoIPage.getRecords();
        //获取当前登录用户的信息
        User user = (User)session.getAttribute("data");
        if (user == null){
            model.addAttribute("article",article);
            model.addAttribute("pageIndex",pageIndex);
            model.addAttribute("page",aremarkVoIPage);
            model.addAttribute("aremarkList",aremarkList);
            return "article";
        }
        Integer userId = user.getUserId();
        modClicks(articleId);
        //足迹
        Footmark footmark = Footmark.builder()
                .footmarkName(article.getArticleTitle())
                .userId(userId)
                .addtime(new Date())
                .build();
        List<Footmark> footmarkList = footmarkService.getAll();
        if (footmarkList.size() == 0){
            addFootmark(footmark);
        }else {
            for(Footmark f : footmarkList){
                if (f.getFootmarkName().equals(footmark.getFootmarkName()) && f.getUserId().equals(footmark.getUserId())){
                    footmark.setFootmarkId(f.getFootmarkId());
                    footmarkService.modFootmark(footmark);
                }
                else {
                    addFootmark(footmark);
                }
                break;
            }
        }
        Integer collectStatus = articleCollectService.getArticleCollectStatus(articleId, userId);
        model.addAttribute("message",message);
        model.addAttribute("collectStatus",collectStatus);
        model.addAttribute("collectNum",collectNum);
        model.addAttribute("article",article);
        model.addAttribute("pageIndex",pageIndex);
        model.addAttribute("page",aremarkVoIPage);
        model.addAttribute("aremarkList",aremarkList);
        return "article";
    }

    /**
     * 文章详情页
     */
    @GetMapping("getArticleShow")
    public String getArticleShow(@RequestParam(value = "articleId") Integer articleId,Model model){
        ArticleDetailVo articleDetailVo = articleService.getArticleById(articleId);
        model.addAttribute("article",articleDetailVo);
        return "redirect:publish";
    }

    /**
     * 用户发表留言
     * @param aremarkVo
     * @param model
     * @param session
     * @return
     */
    @PostMapping("addAremark")
    public String addAremark(AremarkVo aremarkVo, Model model,RedirectAttributes redirectAttributes,HttpSession session){
        //获取当前登录用户的信息
        User user = (User)session.getAttribute("data");
        if (user == null){
            return "redirect:/user/tologin";
        }
        if (aremarkVo.getAremarkContent().equals("")){
            redirectAttributes.addAttribute("message","IsNull");
            return "redirect:getArticleDetailById?articleId="+aremarkVo.getArticleId();
        }
        Aremark aremark = Aremark.builder()
                .articleId(aremarkVo.getArticleId())
                .userId(user.getUserId())
                .aremarkContent(aremarkVo.getAremarkContent())
                .aremarkTime(new Date())
                .build();
        if (aremarkService.addAremark(aremark)>0){
            redirectAttributes.addAttribute("message","Success");
        }else{
            redirectAttributes.addAttribute("message","Failed");
        }
        return "redirect:getArticleDetailById?articleId="+aremarkVo.getArticleId();
    }

    /**
     * 文章添加收藏
     * @param articleId
     * @param session
     * @return
     */
    @GetMapping("/addCollect")
    public String addCollect(Integer articleId,HttpSession session){
        User user = (User)session.getAttribute("data");
        if (user == null){
            return "redirect:/user/tologin";
        }
        ArticleCollect articeCollect = ArticleCollect.builder()
                .userId(user.getUserId())
                .addtime(new Date())
                .articleId(articleId)
                .build();
        articleCollectService.addCollect(articeCollect);
        return "redirect:getArticleDetailById?articleId="+articleId;
    }

    /**
     * 添加用户足迹
     * @param footmark
     * @return
     */
    @GetMapping("/addFootmark")
    public int addFootmark(Footmark footmark){
        return footmarkService.addFootmark(footmark);
    }

    /**
     * 用户访问量
     * @param articleId
     * @return
     */
    @GetMapping("/modClicks")
    public Integer modClicks(Integer articleId){
        Article article = articleService.getById(articleId);
        article.setArticleClicks(article.getArticleClicks()+1);
        return articleService.modArticle(article);
    }

    /**
     * WangEditor图片上传接口
     * @param file
     * @return
     */
    @RequestMapping("/editorUpload")
    @ResponseBody
    public Object  editorUpload(@RequestParam("fileName") MultipartFile file){
       return FileUploadUtil.save(file);
    }
}